<template>
	<div class="holiday">
		<div class="title">节假日管理</div>
		<div class="addAndSearch">
			<Form :model="holidayMsg" label-position="right" :label-width="100" inline >		      
				<Row>
			<Col span="8">
					<FormItem label="日期过滤">
					  <DatePicker type="daterange" placement="bottom-start" placeholder="选择日期范围" style="width: 200px" v-model="filterDate" @on-clear="data = lists"></DatePicker>
					</FormItem>
			</Col>
			<Col span="8">
				<FormItem>
					<Button type="primary" @click="filter">查询</Button>
					<Button type="info" @click="isAdd = true">新增</Button>
				</FormItem>
			</Col>
		</Row>
		  </Form>
		</div>
		<div class="holiday-table">
		  <Table border ref="selection" :columns="columns" :data="data"  height="500" @on-selection-change="select"></Table>
			<Button type="primary" class="clear" @click="clearSelected">清除</Button>
	  </div>
		<Modal
		title="节假日信息修改"
		v-model="isEdit"
		class-name="vertical-center-modal">
	  <Form label-position="right" :label-width="100">
		<FormItem label="日期" required>
			<DatePicker type="daterange" placement="bottom-start" placeholder="选择日期范围" style="width: 200px" v-model="editTimes"></DatePicker>
		</FormItem>
		<FormItem label="类型">
			<Select v-model="type" style="width:200px">
				<Option value="工作日">工作日</Option>
				<Option value="休息日">休息日</Option>
			</Select>
		</FormItem>
		<FormItem label="法定节假日">
			<Checkbox v-model="isHoliday"></Checkbox>
		</FormItem>
		<FormItem label="备注" required>
			<Input v-model="remark" style="width: 200px" :maxlength="35" placeholder="最多输入35个字符"></Input>
		</FormItem>
		</Form>
		<div slot="footer">
			<Button type="default" @click="isEdit=false">取消</Button>
			<Button type="primary" @click="keepEdit">保存</Button>
		</div>
	</Modal>
		<Modal
		title="新增节假日信息"
		v-model="isAdd"
		class-name="vertical-center-modal">
	  <Form label-position="right" :label-width="100" :model="holidayMsg">
		<FormItem label="日期" required>
			<DatePicker type="daterange" placement="bottom-start" placeholder="选择日期范围" style="width: 200px" v-model="holidayMsg.times" ></DatePicker>
		</FormItem>
		<FormItem label="类型" required>
			<Select v-model="holidayMsg.type" style="width:200px">
				<Option value="工作日">工作日</Option>
				<Option value="休息日">休息日</Option>
			</Select>
		</FormItem>
		<FormItem label="法定节假日">
		   <Checkbox v-model="holidayMsg.isHoliday"></Checkbox>
		</FormItem>
		<FormItem label="备注" required>
			<Input v-model="holidayMsg.remark" style="width: 200px" :maxlength="35" placeholder="最多输入35个字符"></Input>
		</FormItem>
		</Form>
		<div slot="footer">
			<Button type="default" @click="isAdd=false">取消</Button>
			<Button type="primary" @click="add">确定</Button>
		</div> 
	</Modal>
	</div>
</template>

<script>
import { mapActions, mapMutations, mapState, mapGetters } from 'vuex'
export default {
  data() {
    return {
      holidayMsg: { 
        times: "",
        type: "",
        isHoliday: false,
        remark: ""
      },
      filterDate: [],
      isFilter: false,
      isEdit: false, //编辑框弹出
      isAdd: false, //新增对话框
      columns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "日期",
          key: "times",
          sortable: true,
          align: "center",
          filters: [
            {
              label: "已过",
              value: 1
            },
            {
              label: "未过",
              value: 2
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            //过滤已过时间与未过时间
            const endDate = new Date(row.times.split(" - ")[1]);
            const today = new Date();
            if (value === 0) {
              return endDate <= today || endDate > today;
            } else if (value === 1) {
              return endDate <= today;
            } else {
              return endDate > today;
            }
          }
        },
        {
          title: "天数（天）",
          key: "days",
          align: "center",
          render: (h, params) => {    //自动计算天数
            const times = params.row.times.split(" - ");
            const days =
              (new Date(times[1]) - new Date(times[0])) / 1000 / 3600 / 24 + 1;
            return h("span", days);
          }
        },
        {
          title: "类型",
          key: "type",
          filters: [
            {
              label: "工作日",
              value: 1
            },
            {
              label: "休息日",
              value: 2
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            if (value === 0) {
              return row.type == "工作日" || row.type == "休息日";
            } else if (value === 1) {
              return row.type == "工作日";
            } else {
              return row.type == "休息日";
            }
          },
          align: "center"
        },
        {
          title: "法定节假日",
          key: "isHoliday",
          align: "center",
          filters: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 2
            }
          ],
          filterMultiple: false,
          filterMethod(value, row) {
            if (value === 0) {
              return row.isHoliday == "是" || row.isHoliday == "否";
            } else if (value === 1) {
              return row.isHoliday == "是";
            } else {
              return row.isHoliday == "否";
            }
          }
        },
        {
          title: "备注",
          key: "remark",
          align: "center"
        },
        {
          title: "操作",
          key: "handle",
          width: 150,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h("Button", {
                props: {
                  type: "primary",
                  size: "small",
                  icon: "edit"
                },
                style: {
                  marginRight: "5px",
                  fontSize: "14px",
                  width: "39px"
                },
                on: {
                  click: () => {
                    this.edit(params.row);
                  }
                }
              }),
              h("Button", {
                props: {
                  type: "error",
                  size: "small",
                  icon: "trash-a"
                },
                style: {
                  fontSize: "14px",
                  width: "39px"
                },
                on: {
                  click: () => {
                    this.remove(params.row.id);
                  }
                }
              })
            ]);
          }
        }
      ],
      remark: "",
      editTimes: "",
      type: "",
      isHoliday: false,
      editId: 0,
      selectedId: [], //选中列表
      data: []
    };
  },
  methods: {
    ...mapMutations(['GET_HOLIDAYMSG', 'DELETE_HOLIDAYMSG','EDIT_HOLIDAYMSG']),
		...mapActions(['getHolidayMsg','addHoliday','removeHoliday','editHoliday']),
    getData() { //获取数据
      this.getHolidayMsg().then(res => {
        this.GET_HOLIDAYMSG(res)
        this.data = this.lists
      }).catch(err=>{
        this.$Notice.error({title:'失败', desc: '获取失败!'})
			})
    },
    add() { //新增
      if (!this.holidayMsg.times[0] || !this.holidayMsg.type || !this.holidayMsg.remark) {
        this.$Message.info("请完善表格内容");
        return;
      }
      const params = {
        type: this.holidayMsg.type === "工作日" ? 0 : 1,
        legal: this.holidayMsg.isHoliday ? 1 : 0,
        note: this.holidayMsg.remark,
        startDate: this.holidayMsg.times[0].getTime() / 1000,
        endDate: this.holidayMsg.times[1].getTime() / 1000
      };
      this.addHoliday(params).then(res => {
      }).catch(err => {
				this.$Notice.error({title:'失败', desc: '新增节假日信息失败!'})
      })
      this.holidayMsg = {
        times: "",
        type: "",
        isHoliday: false,
        remark: ""
      };
      this.isAdd = false;
    },
    remove(id) {  //删除
      this.$Modal.confirm({
        content: "是否确认删除该项记录",
        onOk: () => {
          this.removeHoliday(id).then(res => {
            this.DELETE_HOLIDAYMSG(id);
          }).catch(err=>{
						this.$Notice.error({title:'失败', desc: '删除失败!'})
					});
        }
      });
    },
    edit(row) {   //编辑修改
      this.isEdit = true;
      this.remark = row.remark;
      this.editTimes = row.times.split(" - ").map(item => {
        return new Date(item);
      });
      this.type = row.type;
      this.isHoliday = row.isHoliday === "是" ? true : false;
      this.editId = row.id;
    },
    keepEdit() {  //保存编辑修改
      let isDate = this.editTimes.every(item => {
        return item instanceof Date;
      });
      if (!isDate) {
        this.$Message.info("请选择正确的日期范围");
        this.isEdit = true;
        return 
      } else if(!this.remark) {
        this.$Message.info("备注不能为空");
        this.isEdit = true;
        return 
      } else {
        const params = {
          id: this.editId,
          type: this.type === "工作日" ? 0 : 1,
          legal: this.isHoliday ? 1 : 0,
          note: this.remark,
          startDate: this.editTimes[0].getTime() / 1000,
          endDate: this.editTimes[1].getTime() / 1000
        };
        this.editHoliday(params).then(res => {
          this.EDIT_HOLIDAYMSG(params)
        }).catch(err=>{
					this.$Notice.error({title:'失败', desc: '修改信息失败!'})
				});
        this.isEdit = false;
      }
    },
    filter() {    //点击查询按钮
      if (!this.filterDate[0]) {
        this.$Message.info("请输入要查询的日期范围");
        return;
      }
      let startDate = +new Date(this.filterDate[0]);
      let endDate = +new Date(this.filterDate[1]);
      this.data = this.lists.filter(item => {
        const time = +new Date(item.times.substr(0, 10));
        return time > startDate && time < endDate;
      });
    },
    select(selection) {
      this.selectedId = selection.map(item => {
        return item.id;
      });
    },
    clearSelected() {   //清除已选项
      if (!this.selectedId.length) {
        this.$Message.info("没有选中的记录");
        return;
      }
      this.$Modal.confirm({
        content: "是否确认删除所有选中记录",
        onOk: () => {
          this.removeHoliday(this.selectedId.join()).then(res => {
            if(res.status == 204) {
              this.DELETE_HOLIDAYMSG(this.selectedId)
              this.selectedId = []
            }else {
              console.log('fail')
					    this.$Notice.error({title:'失败', desc: '删除信息失败!'})
            }
          });
        }
      });
    }
  },
  created() {
    this.getData();
  },
  computed: {
    ...mapState({
      lists: ({holiday}) => holiday.lists
    })
  }
};
</script>

<style lang="less" scoped>
.holiday {
  .title {
    font-weight: 500;
    height: 60px;
    line-height: 40px;
    font-size: 20px;
    padding: 20px 0 0 20px;
    border-bottom: 1px solid #ccc;
  }
  .addAndSearch {
    margin: 60px 100px;
  }
  .holiday-table {
    margin: 0 100px;
  }
  .clear {
    text-align: right;
    margin-top: 20px;
  }
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
    .ivu-modal {
      top: 0;
    }
  }
}
</style>